package model.location.calculator;

import model.OnScreen;
import model.location.Coordinate;
import model.location.Dimension;
import model.location.ScreenArea;
import model.location.WorldCoordinate;
import model.snippet.Snippet;

/**
 * Handles the conversion of a world area to it's screen representation.
 */
public class ScreenLocationCalculator 
{
	private static float scale;
	
	/**
	 * Sets the screen area of a snippet by it's world area.
	 * @param snippet The snippet to edit.
	 * @return The edited snippet.
	 */
	public static Snippet calculateScreenArea(Snippet snippet)
	{
		Coordinate screenCoord = calculateScreenCoordinate((WorldCoordinate) snippet.getWorldArea().getCoordinate());
		Dimension screenDimension = calculateScreenDimension(snippet.getWorldArea().getDimension());
		
		snippet.setScreenArea(new ScreenArea(screenCoord, screenDimension));
		return snippet;
	}
	
	/**
	 * Calculates the scale that represents the ratio between a world area and it's value on screen.
	 */
	public static void calculateScale()
	{
		float width = OnScreen.getInstance().getLowerRight().getX() -  OnScreen.getInstance().getUpperLeft().getX();
		
		scale = width / (float) OnScreen.getInstance().getPreviewDimension().getWidth();
	}
	
	/**
	 * Calculates the screen dimension of given world dimension according to the current scale.
	 * @param dimension The world dimension.
	 * @return The screen dimension representation.
	 */
	private static Dimension calculateScreenDimension(Dimension dimension)
	{
		float width = (dimension.getWidth() / scale);
		float height = (dimension.getHeight() / scale);
		Dimension dim = new Dimension(width, height);
		
		return dim;
	}
	
	/**
	 * Calculates the screen coordinate of given world coordinate according to the current scale
	 * @param coordinate The world Coordinate.
	 * @return The screen coordinate representation.
	 */
	private static Coordinate calculateScreenCoordinate(WorldCoordinate coordinate)
	{
		float xOffset = coordinate.getX() - OnScreen.getInstance().getUpperLeft().getX();
		float yOffset = OnScreen.getInstance().getUpperLeft().getY() - coordinate.getY();
		
		float xPixelOffset = (xOffset / scale);
		float yPixelOffset = (yOffset / scale);
		
		Coordinate screenCoordinate = new Coordinate(xPixelOffset, yPixelOffset);
		
		return screenCoordinate;
	}
}
